<template>
  <div>
    <div
      slot="header"
      class="clearfix"
    >
      <div
        class="card-item"
        style="margin-bottom:1rem;"
      >
        <el-form
          :inline="true"
          style="margin-bottom:-1rem"
          :model="impalaForm"
          label-position="left"
          label-width="100px"
        >
          <el-form-item label="选择集群：">
            <el-select
              v-model="impalaForm.cmFlag"
              size="small"
              placeholder="选择集群"
              class="filter-item"
              @change="cmCheck"
            >
              <el-option
                v-for="item in cmList"
                :key="item.cmFlag"
                :label="item.cmName"
                :value="item.cmFlag"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="选择子集群：">
            <el-select
              v-model="impalaForm.clusterFlag"
              size="small"
              placeholder="选择子集群"
              class="filter-item"
            >
              <el-option
                v-for="item in clusterList"
                :key="item.value"
                :label="item.lable"
                :value="item.value"
              />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="选择TOP值：">
              <el-select
                v-model="impalaForm.topData"
                size="small"
                placeholder="选择TOP"
                class="filter-item"
              >
                <el-option
                  v-for="item in topList"
                  :key="item"
                  :label="item"
                  :value="item == '全部' ? 0 : item"
                />
              </el-select>
            </el-form-item> -->
          <el-form-item>
            <el-button
              v-if="applyType"
              type="primary"
              @click="search"
            >搜
              索
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="!applyType"
              type="primary"
              :loading="true"
            >搜索中
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="display: grid; grid-template-columns: repeat(2,1fr);gap: 1rem;">
        
        <div
          class="card-item"
          style="height: 180px;"
        >
          <!-- 使用率超过80%为异常资源 -->
          <div class="title-row">
            <span class="title-row-bar">
              异常资源池信息
            </span>
          </div>
          <span style="font-size:x-small;"> (使用率超过80%为异常资源)</span>
          <div
            style="display:grid; grid-template-columns: repeat(2,1fr);gap: 0.6rem; margin-top: 10px; height: 100px;"
          >
            <InfoCard
              title="异常资源池总数"
              :count="resTotal"
              @click="()=>{
                selectResPool = true
                abnormalDialogVisible = true
              }"
            />
            <InfoCard
              title="异常总数"
              :count="errorTotal"
              @click="()=>{
                selectResPool = false
                abnormalDialogVisible = true
              }"
            />
          </div>
        </div>
        <div
          class="card-item"
          style="height: 180px;"
        >
          <div v-if="cakeFlag">
            <div
              id="impalaCake"
              style="width:100%;height:180px"
            />
          </div>
          <div
            v-if="!cakeFlag"
            style="text-align:center"
          >
            <img
              :src="img"
              alt=""
              style="width:260px"
            >
          </div>
        </div>
      </div>

      <div
        class="card-item"
        style="margin-top: 1rem;"
      >
        <div
          class="title-row"
          style="padding:10px"
        >
          <span class="title-row-bar">
            impala内存使用
          </span>
        </div>
        <el-form
          :inline="true"
          size="small"
          label-width="220px"
        >
          <el-form-item label="查询时间:">
            <el-date-picker
              v-model="memoryValue"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              @change="memoryChange"
            />
          </el-form-item>
        </el-form>
        <div v-if="impalaNcFlag">
          <div
            id="impalaMemory"
            style="width:100%;height:320px"
          />
        </div>
        <div
          v-else
          style="text-align:center"
        >
          <img
            :src="img"
            alt=""
            style="width:300px"
          >
        </div>
      </div>
      <div
        style="margin-top: 1rem;"
        class="card-item"
      >
        <div
          v-if="crud.props.searchToggle"
          class="crud-group"
        >
          <!-- 搜索 -->
          <el-input
            v-model="query.poolName"
            clearable
            size="small"
            placeholder="资源池"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="toQuery"
          />
          <rrOperation :crud="crud" />
        </div>
        <crudOperation
          show=""
          :permission="permission"
        />
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
        >
          <el-table-column
            label="集群名称"
            prop="cmName"
            show-overflow-tooltip
          />
          <el-table-column
            label="子集群名称"
            prop="clusterName"
            show-overflow-tooltip
          />
          <el-table-column
            label="资源池"
            prop="poolName"
            show-overflow-tooltip
          />
          <el-table-column
            label="使用内存(GB)"
            prop="usedGB"
            show-overflow-tooltip
          />
          <el-table-column
            label="最大内存(GB)"
            prop="maxGB"
            show-overflow-tooltip
          />
          <el-table-column
            label="时间"
            prop="createTime"
            show-overflow-tooltip
          />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="used(scope.row)"
              >查看图例</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <pagination />
        </div>
      </div>
      
      <AbnormalDialog
        :dialog-visible="abnormalDialogVisible"
        :is-res-pool="selectResPool"
        resource="impala"
        :cm-flag="impalaForm.cmFlag"
        :cluster-flag="impalaForm.clusterFlag"
        @close="abnormalDialogVisible = false"
      />

      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="flags"
        :before-close="handleClose1"
        width="1200px"
        title="Impala详情"
      >
        <div v-if="cellData.maxGB != '未设置'">
          <el-date-picker
            v-model="value1"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="checkTime"
          />
          <div
            id="impalaUsed"
            style="width:100%;height:320px"
          />
        </div>
        <div
          v-if="cellData.maxGB == '未设置'"
          style="color:red"
        >因为未设置最大内存数，所以暂不支持查看使用率</div>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            @click="handleClose1"
          >关 闭</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import impala from '@/api/monitor/resource'
import monitor from '@/api/monitor/monitor'
import CRUD, { presenter, header, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import * as echarts from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'
import nullData from '@/assets/images/nullData.webp'
import pagination from '@crud/Pagination'
import dateUtils from '@/utils/date'
import InfoCard from './components/InfoCard.vue'
import AbnormalDialog from './components/AbnormalDialog.vue'

const defaultCrud = CRUD({
  title: 'impala',
  url: 'monitor_api/cmResouce/selImpalaPoolDetail'
})

export default {
  name: 'Impala',
  components: { crudOperation, rrOperation, pagination, InfoCard, AbnormalDialog },
  mixins: [presenter(defaultCrud), header(), crud()],
  data() {
    return {
      impalaForm: {
        cmFlag: '',
        clusterFlag: '',
        topData: 0
      },
      abnormalDialogVisible: false,
      selectResPool: false,
      cmList: ['集群A', '集群B', '集群C'],
      topList: [5, 10, 15, '全部'],
      tableList: [
        {
          name: 'aa',
          modelName: 'XXX',
          userDep: 'XXX'
        },
        {
          name: 'bb',
          modelName: 'XXX',
          userDep: 'XXX'
        },
        {
          name: 'cc',
          modelName: 'XXX',
          userDep: 'XXX'
        }
      ],
      permission: {
        add: ['add'],
        edit: ['edit'],
        del: ['del']
      },
      queryOptions: [{ columnName: 'poolName', columnValue: '资源池', inputType: 1 }],
      resTotal: '',
      errorTotal: '',
      abnormalData: [],
      flags: false,
      value1: '',
      startTime: '',
      endTime: '',
      cellData: {},
      currentPage: 1, // 当前页码
      total: 20, // 总条数
      pageSize: 10, // 每页的数据条数
      img: nullData,
      cakeFlag: true,
      impalaNcFlag: true,
      cmFlag: '',
      clusterFlag: '',
      applyType: true,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      memoryValue: [
        dateUtils.getPastTimeFull(1),
        dateUtils.getNowDateFull()
      ],
      memoryStart: dateUtils.getPastTimeFull(1),
      memoryEnd: dateUtils.getNowDateFull()
    }
  },
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler: function (val, oldVal) {
        if (val.path === '/appResource') {
          this.cmFlag = this.$route.query.cmFlag
          this.clusterFlag = this.$route.query.clusterFlag
          this.selAllCm()
        }
      }
    }
  },
  created() {
    // this.crud.queryList = this.queryOptions
    // this.selAllCm()
    // this.getTotal()
  },
  mounted() {
    this.selAllCm()
  },
  methods: {
    selAllCm() {
      const centerId = sessionStorage.getItem('sysKernelId')
      const reqData = { 'centerId': centerId }
      monitor.selAllCm(reqData).then(res => {
        this.cmList = res
        this.impalaForm.cmFlag = res[0].cmFlag
        this.impalaForm.clusterFlag = res[0].clusterFlag
        this.selClusterInfos()
      })
    },
    selClusterInfos() {
      this.getTotal()
      this.getCake()
      this.getTOP()
      this.query['cmFlag'] = this.impalaForm.cmFlag
      this.query['clusterFlag'] = this.impalaForm.clusterFlag
      this.crud.refresh()
    },
    cmCheck(value) {
      this.impalaForm.clusterFlag = this.cmList.find(item => item.cmFlag === value).clusterFlag
      this.selClusterInfos()
    },
    // childrenCm(){
    //   this.getTotal()
    //   this.getTOP()
    //   this.getCake()
    //   this.query['cmFlag']=this.impalaForm.cmFlag
    //   this.query['clusterFlag']=this.impalaForm.clusterFlag
    //   this.crud.refresh()
    // },
    getTOP() {
      this.impalaNcFlag = true
      const data = { 'cmFlag': this.impalaForm.cmFlag, 'clusterFlag': this.impalaForm.clusterFlag, 'topNum': this.impalaForm.topData, startTime: this.memoryStart, endTime: this.memoryEnd }
      impala.topCheck(data).then((res) => {
        const nameList = []
        const seriesData = []
        let impalaX = []
        if (res != null && res.length > 0) {
          res.forEach((item) => {
            nameList.push(item.cmFlag + '-' + item.clusterFlag + '-' + item.poolName)
            const arr = []
            impalaX = []
            item.topList.forEach((val) => {
              impalaX.push(val.createTime)
              arr.push(val.ncPro)
            })
            const obj = { name: item.cmFlag + '-' + item.clusterFlag + '-' + item.poolName, type: 'line', smooth: true, data: arr }
            seriesData.push(obj)
          })
          var chartDom = document.getElementById('impalaMemory')
          var myChart = echarts.init(chartDom)
          var option

          option = {
            title: {
              text: 'impala内存'
            },
            legend: {
              data: nameList
            },
            tooltip: {
              trigger: 'axis'
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: impalaX,
              boundaryGap: false
            },
            yAxis: {
              type: 'value',
              name: '%',
              max: 100,
              splitNumber: 10
            },
            series: seriesData
          }

          option && myChart.setOption(option, true)
          const erd = elementResizeDetectorMaker()
          erd.listenTo(document.getElementById('impalaMemory'), (element) => {
            myChart.resize()
          })
        } else {
          this.impalaNcFlag = false
        }
      })
    },
    // checkTop(){
    //   this.getTOP()
    // },
    getTotal() {
      const data = { 'cmFlag': this.impalaForm.cmFlag, 'clusterFlag': this.impalaForm.clusterFlag }
      impala.getCount(data).then((res) => {
        this.abnormalData = res
        if (res.length === 0) {
          this.resTotal = '0'
          this.errorTotal = '0'
        } else {
          this.resTotal = res.length.toString()
          const arr = []
          res.forEach((item) => {
            arr.push(item.countA)
          })
          this.errorTotal =
          arr.reduce((a, b) => a * 1 + b * 1).toString()
        }
      })
    },
    getCake() {
      this.cakeFlag = true
      const data = { 'cmFlag': this.impalaForm.cmFlag, 'clusterFlag': this.impalaForm.clusterFlag }
      impala.getAllCount(data).then((res) => {
        this.applyType = true
        if (res != null) {
          const titleName = res.cmName + '-' + res.clusterName
          var myChart = echarts.init(document.getElementById('impalaCake'))
          var option

          option = {
            title: {
              text: titleName === '-' ? '全部集群' : titleName,
              left: 'left',
              textStyle: {
                fontSize: 16
              }
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              left: 'left',
              orient: 'vertical',
              top: '15%',
              textStyle: {
                fontSize: 12
              }
            },
            series: [
              {
                name: '',
                type: 'pie',
                radius: '50%',
                center: ['55%', '40%'],
                data: [
                  { value: res.countA, name: '使用率高于80%;共' + res.countA + '个', itemStyle: { color: '#F56C6C' } },
                  { value: res.countB, name: '使用率大于50%,低于80%;共' + res.countB + '个', itemStyle: { color: '#E6A23C' } },
                  { value: res.countC, name: '使用率低于50%;共' + res.countC + '个', itemStyle: { color: '#67C23A' } }
                ],
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          option && myChart.setOption(option, true)
          const erd = elementResizeDetectorMaker()
          erd.listenTo(document.getElementById('impalaCake'), (element) => {
            myChart.resize()
          })
        } else {
          this.cakeFlag = false
        }
      })
    },
    used(row) {
      this.startTime = ''
      this.endTime = ''
      this.cellData = row
      this.flags = true
      this.getImpalaSyl()
    },
    handleClose1() {
      this.flags = false
    },
    checkTime() {
      this.startTime = this.value1[0]
      this.endTime = this.value1[1]
      this.getImpalaSyl()
    },
    getImpalaSyl() {
      const obj = { cmFlag: this.cellData.cmFlag, clusterFlag: this.cellData.clusterFlag, userId: this.cellData.userId, poolName: this.cellData.poolName, queue: this.cellData.queue, startTime: this.startTime, endTime: this.endTime }
      impala.getImpalaSyl(obj).then((res) => {
        // let nameList=[]
        const seriesData = []
        let impalaX = []
        const max = []
        const used = []
        const fpMax = []
        const fpUsed = []
        res.forEach((item) => {
          // nameList.push(item.cmFlag+'-'+item.clusterFlag+'-'+item.poolName)
          const arr = []
          const list = []
          impalaX = []
          item.topList.forEach((val) => {
            impalaX.push(val.createTime)
            arr.push(val.ncPro)
            max.push(val.maxGB)
            used.push(val.usedGB)
            list.push(val.fpPro)
            fpMax.push(val.totalGB)
            fpUsed.push(val.maxGB)
          })
          const obj = { name: item.cmFlag + '-' + item.clusterFlag + '-' + item.poolName + '使用率', type: 'line', smooth: true, data: arr }
          const obj1 = { name: item.cmFlag + '-' + item.clusterFlag + '-' + item.poolName + '分配率', type: 'line', smooth: true, data: list }
          seriesData.push(obj, obj1)
        })
        var chartDom = document.getElementById('impalaUsed')
        var myChart = echarts.init(chartDom)
        var option

        option = {
          title: {
            text: 'impala内存'
          },
          legend: {
            // data: nameList,
            type: 'scroll',
            left: '30%'
          },
          tooltip: {
            trigger: 'axis',
            formatter: (val) => {
              const cluster1 = val[0]
              const cluster2 = val[1]
              return (cluster1.name + '<br>' + cluster1.seriesName + '<br>' + cluster1.value + '%(已使用' + used[cluster1.dataIndex] + 'GB/共' + max[cluster1.dataIndex] + 'GB)<br>' + cluster2.seriesName + '<br>' + cluster2.value + '%(已分配' + fpUsed[cluster2.dataIndex] + 'GB/共' + fpMax[cluster2.dataIndex] + 'GB)')
              // return (cluster1.name+'<br>'+cluster1.seriesName+'<br>共'+max[cluster1.dataIndex]+'GB;使用'+used[cluster1.dataIndex]+'GB;占'+cluster1.value+'%<br>'+cluster2.seriesName+'<br>共'+fpMax[cluster2.dataIndex]+'GB;使用'+fpUsed[cluster2.dataIndex]+'GB;占'+cluster2.value+'%')
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: impalaX
          },
          yAxis: {
            type: 'value',
            name: '%'
          },
          series: seriesData
        }

        option && myChart.setOption(option, true)
        const erd = elementResizeDetectorMaker()
        erd.listenTo(document.getElementById('impalaUsed'), (element) => {
          myChart.resize()
        })
        // 分配率
        // var chartDom1 = document.getElementById('impalaFp');
        // var myChart1 = echarts.init(chartDom1);
        // var option1;

        // option1 = {
        //   legend: {
        //     data: nameList
        //   },
        //   tooltip: {
        //     trigger: 'axis'
        //   },
        //   grid: {
        //     left: '3%',
        //     right: '4%',
        //     bottom: '3%',
        //     containLabel: true
        //   },
        //   xAxis: {
        //     type: 'category',
        //     data: impalaX
        //   },
        //   yAxis: {
        //     type: 'value',
        //     name:'%',
        //   },
        //   series: fpSeries
        // };

        // option1 && myChart1.setOption(option1,true);
        // const erd1 = elementResizeDetectorMaker();
        // erd1.listenTo(document.getElementById("impalaFp"), (element) => {
        //   myChart1.resize();
        // });
      })
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    search() {
      this.memoryStart = ''
      this.memoryEnd = ''
      this.applyType = false
      this.getTotal()
      this.getTOP()
      this.getCake()
      this.query['cmFlag'] = this.impalaForm.cmFlag
      this.query['clusterFlag'] = this.impalaForm.clusterFlag
      this.crud.refresh()
    },
    memoryChange() {
      if (this.memoryValue) {
        this.memoryStart = this.memoryValue[0]
        this.memoryEnd = this.memoryValue[1]
      } else if (this.memoryValue == null) {
        this.memoryStart = ''
        this.memoryEnd = ''
      }
      this.getTOP()
    }
  }
}
</script>

<style scoped lang="scss">
.cardBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  width: 120px;
  padding: 10px;
}

.error {
  font-size: 24px;
  color: white;
  border: 1px solid #dedede;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.04);
  border-radius: 5px;
  text-align: center;
  background-color: #F56C6C;
  width: 80%;
}

.total {
  font-size: 24px;
  color: white;
  border: 1px solid #dedede;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.04);
  border-radius: 5px;
  text-align: center;
  background-color: #409EFF;
  width: 80%;
}

</style>
